<?php

namespace app\mini\model;

use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;

class CustomerOrder extends Model
{
	use ActionRecordTrait;

    /**
     * 表名
     * @var string
     */
    protected $name = 'shop_order';
    protected $deleteTime = 'deleted_at';
    protected $defaultSoftDelete = 0;

    /**
     * 获取订单列表
     * @param  array $request 请求参数
     * @return array
     * @author hz
     * @create 2021-06-1
     */
    public function getDataList($request)
    {
        try {
            $uid = $request['customer_id'] ?? 0;
            if(!$uid)
            {
            	return ['error' => '您还未认证,请先认证'];
            }
            $where   = [];
            $where[] = ['uid', '=', $uid];

            // 订单列表
            $field = ['id,order_no,status,create_time,total_amount,discount_amount,pay_amount'];
            $list  = Db::name('shop_order')->field($field)->where($where)->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->order('id DESC')->select()->toArray();
            $dataCount = Db::name('shop_order')->where($where)->count();
           
            // 订单商品
            $orderIdArr = array_column($list, 'id');
            $og_where = [
                ['order_id', 'in', $orderIdArr]
            ];
            $og_field = ['order_id,sum(pay_price * number) as order_goods_price,goods_name,number'];
            $orderGoodsList = Db::name('shop_order_goods')
                        ->field($og_field)
                        ->where($og_where)
                        ->group('order_id')->select()->toArray();
            $orderGoodsList = array_column($orderGoodsList, null, 'order_id');
            // print_r($orderGoodsList);exit;
            if ($list) {
                foreach($list as &$v){
                    $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                    $v['goods'] = isset($orderGoodsList) ? array_values($orderGoodsList) : [];
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return ['data' => $data];
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

}